import java.util.ArrayList;
import java.util.List;

public class TicketService implements Loggable {
    private List<Ticket> ticketList = new ArrayList<>();
    private static final String TICKET_FILE = "tickets.txt"; // 存储票务数据的文件

    // 构造方法：初始化时从文件加载票务数据
    public TicketService() {
        ticketList = FileUtil.readTicketsFromFile(TICKET_FILE);
    }

    // 售票
    public Ticket sellTicket(Show show, List<Seat> seats) {
        // 1. 检查座位是否可用
        for (Seat seat : seats) {
            if (!show.getHall().checkSeatAvailable(seat.getRow(), seat.getCol())) {
                return null;
            }
        }

        // 2. 锁定座位
        if (!show.getHall().lockSeats(seats)) {
            return null;
        }

        // 3. 计算总价（单票价 × 座位数）
        double totalPrice = show.getPrice() * seats.size();

        // 4. 创建票
        Ticket ticket = new Ticket(show, seats, totalPrice);

        // 5. 关联场次和票
        show.getTickets().add(ticket);
        ticketList.add(ticket);

        // 6. 记录日志
        logOperation("售票：" + ticket.getTicketId() + "，影片：" + show.getMovie().getName());
        return ticket;
    }

    // 退票
    public boolean refundTicket(String ticketId) {
        for (Ticket ticket : ticketList) {
            if (ticket.getTicketId().equals(ticketId) && ticket.canRefund()) {
                // 1. 标记为已退票
                ticket.setRefunded(true);

                // 2. 解锁座位
                ticket.getShow().getHall().unlockSeats(ticket.getSeats());

                // 3. 从场次中移除票
                ticket.getShow().getTickets().remove(ticket);

                // 4. 记录日志
                logOperation("退票：" + ticketId + "，影片：" + ticket.getShow().getMovie().getName());
                return true;
            }
        }
        return false;
    }

    // 保存票务数据到文件
    public void saveTickets() {
        FileUtil.writeTicketsToFile(ticketList, TICKET_FILE);
    }
}
    